import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class CTPServer {
    private static final int PORT = 8088;
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("CTP Server started on port " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new ClientHandler(clientSocket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ClientHandler extends Thread {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        public void run() {
            try (InputStream input = clientSocket.getInputStream();
                 DataInputStream dis = new DataInputStream(input)) {

                // 读取客户端发送的数据长度
                int dataLength = dis.readInt();
                byte[] buffer = new byte[BUFFER_SIZE];
                
                // 读取实际数据
                int bytesRead = dis.read(buffer, 0, Math.min(dataLength, BUFFER_SIZE));
                String receivedData = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);

                System.out.println("Received from " + clientSocket.getRemoteSocketAddress() + ":");
                System.out.println(receivedData);

                // 发送确认响应
                String response = "Data received (" + bytesRead + " bytes)";
                DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
                dos.writeUTF(response);
                dos.flush();

            } catch (IOException e) {
                System.err.println("Error handling client: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("Error closing socket: " + e.getMessage());
                }
            }
        }
    }
}